package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.domain.dto.UpdatePersonalInfoRequest;
import com.ruoyi.merchant.domain.vo.PersonalInfoVO;
import com.ruoyi.merchant.mapper.MerchantMapper;
import com.ruoyi.merchant.service.MerchantProfileService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class MerchantProfileServiceImpl implements MerchantProfileService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired private RedisCache redisCache;
    @Autowired private TokenService tokenService;

    @Autowired
    private MerchantMapper merchantMapper;

    private static final String SMS_CODE_KEY = "sms_code:"; // 和登录完全一致

    @Override
    public PersonalInfoVO getPersonalInfo(Long userId) {
        SysUser u = sysUserMapper.selectUserById(userId);
        if (u == null || "2".equals(u.getDelFlag())) {
            throw new ServiceException("用户不存在或已删除");
        }

        PersonalInfoVO vo = new PersonalInfoVO();
        vo.setUserId(u.getUserId());
        vo.setUserName(u.getUserName());
        vo.setNickName(u.getNickName());
        vo.setPhonenumber(u.getPhonenumber());
        vo.setEmail(u.getEmail());
        vo.setSex(u.getSex());
        vo.setSexName(sexNameOf(u.getSex()));
        // 头像是完整URL，直接原样返回
        vo.setAvatar(u.getAvatar());
        return vo;
    }

    private String sexNameOf(String sex) {
        if ("0".equals(sex)) return "男";
        if ("1".equals(sex)) return "女";
        if ("2".equals(sex)) return "未知";
        return "未知";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePersonalInfo(Long userId, UpdatePersonalInfoRequest req) {
        SysUser db = sysUserMapper.selectUserById(userId);
        if (db == null || "2".equals(db.getDelFlag())) {
            throw new ServiceException("用户不存在");
        }

        String newPhone = StringUtils.trimToNull(req.getPhonenumber());
        String oldPhone = StringUtils.trimToNull(db.getPhonenumber());
        boolean changePhone = newPhone != null && !newPhone.equals(oldPhone);

        if (changePhone) {
            // 1) 验证码校验（与你登录一致）
            if (StringUtils.isEmpty(req.getSmsCode())) {
                throw new ServiceException("验证码不能为空");
            }
            String cacheKey = SMS_CODE_KEY + newPhone;
            String cachedCode = redisCache.getCacheObject(cacheKey);
            if (StringUtils.isEmpty(cachedCode)) throw new ServiceException("验证码已过期，请重新获取");
            if (!cachedCode.equals(org.apache.commons.lang3.StringUtils.deleteWhitespace(req.getSmsCode()))) {
                throw new ServiceException("验证码错误");
            }
            redisCache.deleteObject(cacheKey);

            // 2) merchants 表唯一性校验（排除自己）
            Merchant exist = merchantMapper.selectMerchantByPhone(newPhone);
            Merchant my = merchantMapper.selectMerchantByUserId(userId);
            if (my == null) throw new ServiceException("商家信息不存在");
            if (exist != null && !exist.getMerchantId().equals(my.getMerchantId())) {
                throw new ServiceException("该手机号已被其他商家使用");
            }
        }

        // 3) 更新 sys_user（权威源）
        SysUser upd = new SysUser();
        upd.setUserId(userId);
        if (StringUtils.isNotBlank(req.getNickName())) upd.setNickName(req.getNickName());
        if (StringUtils.isNotBlank(req.getAvatar()))   upd.setAvatar(req.getAvatar());
        if (StringUtils.isNotBlank(req.getEmail()))    upd.setEmail(req.getEmail());
        if (StringUtils.isNotBlank(req.getSex()))      upd.setSex(req.getSex());
        if (changePhone) {
            upd.setPhonenumber(newPhone);
            upd.setUserName(newPhone); // 登录账号=手机号
        }
        upd.setUpdateTime(new Date());
        sysUserMapper.updateUserSelective(upd);

        // 4) 同步 merchants.contact_phone
        if (changePhone) {
            merchantMapper.updateContactPhoneByUserId(userId, newPhone);
            // 旧 token 失效
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) tokenService.delLoginUser(loginUser.getToken());
        }
    }

    @Override
    public void updateAvatar(Long userId, String avatarUrl) {
        int rows = sysUserMapper.updateAvatar(userId, avatarUrl);
        if (rows <= 0) {
            throw new ServiceException("头像更新失败，请稍后再试");
        }
    }
}
